package com.wx.cloud.user.aspect;

import com.wx.cloud.user.model.LoginInfo;
import com.wx.cloud.user.service.LoginInfoService;
import com.wx.cloud.user.utils.IpUtil;
import com.wx.cloud.user.utils.MyDate;
import com.wx.cloud.user.vo.LoginParam;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

@Component
@Aspect
public class ServiceAspect {

    @Autowired
    private LoginInfoService loginInfoService;

    @Pointcut("execution(* com.wx.cloud.user.service.impl.UserServiceImpl.login(..))")
    public void pointcut(){
    }

    //需要切入的信息
    @AfterReturning(returning="rvt", pointcut="pointcut()")
    public void before(JoinPoint joinPoint,String rvt){
        if (rvt != "该用户已被冻结" && rvt != "用户名或密码错误" && rvt != "密码输入错误超过三次，该用户已被冻结") {
            //获取用户ip地址
            ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
            if (attributes == null) {
                return;
            }
            HttpServletRequest request = attributes.getRequest();
            String ip = IpUtil.getIpAddr(request);

            //参数名称
            String[] names = ((MethodSignature) joinPoint.getSignature()).getParameterNames();
            //参数值
            Object[] objects = joinPoint.getArgs();
            Map<String, Object> map = new HashMap<String, Object>();
            for (int i = 0; i < names.length; i++) {
                map.put(names[i], objects[i]);
            }
            LoginParam loginParam = (LoginParam) map.get("loginParam");

            LoginInfo loginInfo = new LoginInfo();
            loginInfo.setLoginIp(ip);
            loginInfo.setUserCode(loginParam.getUserCode());
            loginInfo.setLoginTime(MyDate.getDate());

            loginInfoService.saveLoginInfo(loginInfo);
        }
    }
}
